import random
from datetime import datetime
from get_captcha import get_captcha_code_and_content
from faker import Faker
from flask import Flask, render_template, request, session, make_response, redirect

import config
from extensions import register_extension, db
from orms import StudentORM,Userdb


app = Flask(__name__)

app.config.from_object(config)
register_extension(app)
@app.cli.command()
def create():
    db.drop_all()
    db.create_all()
    faker = Faker(locale="zh-CN")
    for i in range(100):
        student = StudentORM()
        info = faker.simple_profile()
        student.name = info['name']
        student.gender = info['sex']
        student.mobile = faker.phone_number()
        student.address = info['address']
        student.class_name = random.choice(['一班', '二班', '三班'])
        student.save()


@app.route('/')
def index_view():
    is_login = session.get('is_login')  #
    # print('route /',is_login)
    return render_template('admin.html', is_login=is_login)  #







@app.route('/admin')
def admin():
    return render_template('admin.html')

@app.route('/register')
def register_view():
    return render_template('register.html')
@app.route('/login')
def login_view():
    return render_template('/login.html')

@app.post('/api/register')
def register_api():
    # 1. 解析前端传递过来的数据
    data = request.get_json()
    print(data)
    username = data['username']
    password = data['password']
    useradd = Userdb()
    useradd.update(data)
    print(username,password)
    if not all([username, password]):
        return {
            'message': '数据缺失',
            'code': -1
        }
    try:
        print(data)
        useradd.save()
    except Exception as e:
        print(e)
        return {
            'code': -1,
            'msg': '新增数据失败'
        }
    return {
        'code': 0,
        'msg': '新增数据成功'
    }

@app.route('/api/student')
def student_view():
    print(request.args.get('seach'))
    seach=request.args.get('seach')
    page = request.args.get('page', type=int, default=1)
    per_page = request.args.get('per_page', type=int, default=10)
    paginate = StudentORM.query.paginate(page=page, per_page=per_page, error_out=False)
    if not (seach == None or seach == ""):
        paginate = StudentORM.query.filter(StudentORM.name.like(f"%{seach}%")).paginate(page=page, per_page=per_page,
                                                                                        error_out=False)
    items: [StudentORM] = paginate.items

    return {
        'code': 0,
        'msg': '信息查询成功',
        'count': paginate.total,
        'data': [
            {
                'id': item.id,
                'name': item.name,
                'gender': item.gender,
                'mobile': item.mobile,
                'class_name': item.class_name,
                'address': item.address,
                'disable': item.disable,
                'is_del': item.is_del,
                'create_at': item.create_at.strftime('%Y-%m-%d %H:%M:%S'),
                'update_at': item.update_at.strftime('%Y-%m-%d %H:%M:%S'),
            } for item in items
        ]
    }



@app.get('/student_add')
def student_add():
    return render_template('student_add.html')

@app.post('/api/student')
def api_student_post():
    data = request.get_json()
    print(data)
    data['create_at'] = datetime.strptime(data['create_at'], '%Y-%m-%d %H:%M:%S')
    student = StudentORM()
    student.update(data)
    try:
        student.save()
    except Exception as e:
        print(e)
        return {
            'code': -1,
            'msg': '新增数据失败'
        }
    return {
        'code': 0,
        'msg': '新增数据成功'
    }
@app.put('/api/student/<int:sid>')
def api_student_put(sid):
    data = request.get_json()
    data['create_at'] = datetime.strptime(data['create_at'], '%Y-%m-%d %H:%M:%S')
    # student = StudentORM.query.get(sid)
    student = db.get_or_404(StudentORM, sid)
    student.update(data)
    try:
        student.save()
    except Exception as e:
        return {
            'code': -1,
            'msg': '修改数据失败'
        }
    return {
        'code': 0,
        'msg': '修改数据成功'
    }

@app.delete('/api/student/<int:sid>')
def api_student_del(sid):
    student: StudentORM = db.get_or_404(StudentORM, sid)
    try:
        # db.session.delete(student)
        student.is_del = True
        db.session.commit()
    except Exception as e:
        return {
            'code': -1,
            'msg': '删除数据失败'
        }
    return {
        'code': 0,
        'msg': '删除数据成功'
    }



# 生成验证码
@app.get('/get_captcha')
def get_captcha_view():
    # 1. 获取参数
    captcha_uuid = request.args.get("captcha_uuid")
    # 2. 生成验证码
    code, content = get_captcha_code_and_content()

    # 3. 记录数据到数据库（用session代替）
    session['code'] = code
    resp = make_response(content)  # 读取图片的二进制数据做成响应体
    resp.content_type = "image/png"
    # 4. 错误处理

    # 5. 响应返回
    return resp


@app.post('/api/login')
def login_api():
    data = request.get_json()
    user = Userdb()
    user.username = data.get('username')
    user.password = data.get('password')
    result = user.search()
    code = session['code']
    if code != data['captcha']:
        return {
            'message': '验证码错误',
            'code': -1
        }

    if len(result) == 0:
        return {
            'message': '用户不存在或密码错误',
            'code': -1
        }

    session['is_login'] = True  # 记录用户登录
    return {
        'message': '用户登录成功',
        'code': 0
    }


@app.get('/logout')
def logout():
    session.clear()
    return render_template('login.html')


@app.before_request
def filter_request():
    is_login=session.get('is_login',False)
    if is_login == True:
        return None
    if request.path.startswith('/static') or request.path.startswith('/get_captcha') or request.path == '/api/login':
        return None
    else:
        return  render_template('login.html')
        # return redirect('/login')


if __name__ == '__main__':
    app.run()
